<template>
  <div class="my-tasks-wrapper">
    <div class="my-tasks-container">
      <div class="my-tasks-header">
        <h1>我发布的任务</h1>
        <p>查看和管理您发布的所有任务</p>
      </div>

      <div v-if="loading" class="loading">加载中...</div>
      
      <div v-else-if="tasks.length === 0" class="no-tasks">
        <p>您还没有发布任何任务</p>
        <button @click="goToPublish" class="publish-button">发布任务</button>
      </div>
      
      <div v-else class="tasks-list">
        <div 
          v-for="task in tasks" 
          :key="task.taskId" 
          class="task-card"
          @click="showTaskDetail(task)"
        >
          <div class="task-header">
            <h3>{{ task.title }}</h3>
            <span :class="['status-badge', getStatusClass(task.status)]">
              {{ getStatusText(task.status) }}
            </span>
          </div>
          
          <div class="task-content">
            <p class="task-description">{{ task.description }}</p>
            <div class="task-meta">
              <div class="meta-item">
                <span class="meta-label">预算:</span>
                <span class="meta-value">¥{{ task.budget }}</span>
              </div>
              <div class="meta-item">
                <span class="meta-label">发布日期:</span>
                <span class="meta-value">{{ formatDate(task.publishDate) }}</span>
              </div>
            </div>
          </div>
          
          <div class="task-actions">
            <button 
              @click.stop="editTask(task)"
              class="edit-button"
            >
              编辑
            </button>
            <button 
              @click.stop="deleteTask(task.taskId)"
              class="delete-button"
            >
              删除
            </button>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 自定义弹窗 -->
    <MessageModal 
      :visible="modalVisible"
      :title="modalTitle"
      :message="modalMessage"
      :type="modalType"
      @close="closeModal"
      @confirm="handleModalConfirm"
    />
    
    <!-- 任务详情弹窗 -->
    <TaskDetailModal
      :visible="detailModalVisible"
      :task="selectedTask"
      :show-accept-button="false"
      @close="closeDetailModal"
    />
    
    <!-- 编辑任务弹窗 -->
    <div v-if="editModalVisible" class="edit-modal-overlay" @click="closeEditModal">
      <div class="edit-modal-container" @click.stop>
        <div class="edit-modal-header">
          <h3>编辑任务</h3>
          <button class="edit-modal-close" @click="closeEditModal">&times;</button>
        </div>
        <div class="edit-modal-body">
          <form @submit.prevent="updateTask">
            <div class="form-group">
              <label for="title">任务标题:</label>
              <input 
                id="title" 
                v-model="editForm.title" 
                type="text" 
                class="form-control"
                required
              />
            </div>
            
            <div class="form-group">
              <label for="description">任务描述:</label>
              <textarea 
                id="description" 
                v-model="editForm.description" 
                class="form-control"
                rows="4"
                required
              ></textarea>
            </div>
            
            <div class="form-group">
              <label for="budget">预算 (¥):</label>
              <input 
                id="budget" 
                v-model.number="editForm.budget" 
                type="number" 
                step="0.01"
                min="0.01"
                class="form-control"
                required
              />
            </div>
            
            <div class="form-group">
              <label>任务状态:</label>
              <div class="status-options">
                <label class="status-option">
                  <input 
                    type="radio" 
                    v-model="editForm.status" 
                    :value="0" 
                  />
                  待接取
                </label>
                <label class="status-option">
                  <input 
                    type="radio" 
                    v-model="editForm.status" 
                    :value="1" 
                  />
                  进行中
                </label>
                <label class="status-option">
                  <input 
                    type="radio" 
                    v-model="editForm.status" 
                    :value="2" 
                  />
                  已完成
                </label>
                <label class="status-option">
                  <input 
                    type="radio" 
                    v-model="editForm.status" 
                    :value="3" 
                  />
                  已关闭
                </label>
              </div>
            </div>
            
            <div class="edit-modal-footer">
              <button type="button" class="cancel-button" @click="closeEditModal">取消</button>
              <button type="submit" class="save-button">保存</button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import api from '../api/index.js'
import MessageModal from './MessageModal.vue'
import TaskDetailModal from './TaskDetailModal.vue'

const router = useRouter()
const tasks = ref([])
const loading = ref(false)

// 弹窗相关状态
const modalVisible = ref(false)
const detailModalVisible = ref(false)
const editModalVisible = ref(false)
const selectedTask = ref({})
const editForm = ref({
  taskId: null,
  title: '',
  description: '',
  budget: null,
  status: 0
})
const modalTitle = ref('')
const modalMessage = ref('')
const modalType = ref('info')
const successCallback = ref(null)

// 显示弹窗
const showModal = (title, message, type = 'info', callback = null) => {
  modalTitle.value = title
  modalMessage.value = message
  modalType.value = type
  modalVisible.value = true
  successCallback.value = callback
}

// 关闭弹窗
const closeModal = () => {
  modalVisible.value = false
}

// 显示任务详情
const showTaskDetail = async (task) => {
  try {
    // 获取任务详情及评价
    const response = await api.get(`/task/detail-with-evaluation/${task.taskId}`)
    if (response.code === 0) {
      selectedTask.value = response.data.task
      // 添加评价信息到任务对象中
      selectedTask.value.evaluation = response.data.evaluation
      detailModalVisible.value = true
    } else {
      showModal('错误', '获取任务详情失败: ' + response.message, 'error')
    }
  } catch (error) {
    console.error('获取任务详情失败:', error)
    showModal('错误', '获取任务详情失败，请重试', 'error')
  }
}

// 关闭详情弹窗
const closeDetailModal = () => {
  detailModalVisible.value = false
}

// 显示编辑弹窗
const showEditModal = (task) => {
  editForm.value = { ...task }
  editModalVisible.value = true
}

// 关闭编辑弹窗
const closeEditModal = () => {
  editModalVisible.value = false
}

// 处理弹窗确认
const handleModalConfirm = () => {
  if (successCallback.value) {
    successCallback.value()
  }
}

// 跳转到发布任务页面
const goToPublish = () => {
  router.push('/publish-task')
}

// 获取我发布的任务
const fetchMyTasks = async () => {
  loading.value = true
  try {
    const response = await api.get('/task/my')
    if (response.code === 0) {
      tasks.value = response.data
    } else {
      showModal('错误', '获取任务列表失败: ' + response.message, 'error')
    }
  } catch (error) {
    console.error('获取任务列表失败:', error)
    showModal('错误', '获取任务列表失败，请重试', 'error')
  } finally {
    loading.value = false
  }
}

// 编辑任务
const editTask = (task) => {
  showEditModal(task)
}

// 更新任务
const updateTask = async () => {
  try {
    const taskToUpdate = {
      taskId: editForm.value.taskId,
      title: editForm.value.title,
      description: editForm.value.description,
      budget: editForm.value.budget,
      status: editForm.value.status
    }
    
    const response = await api.put('/task/update', taskToUpdate)
    if (response.code === 0) {
      showModal('成功', '任务更新成功！', 'success')
      closeEditModal()
      
      // 更新本地任务列表
      const index = tasks.value.findIndex(t => t.taskId === editForm.value.taskId)
      if (index !== -1) {
        tasks.value[index] = { ...tasks.value[index], ...taskToUpdate }
      }
    } else {
      showModal('错误', '更新任务失败: ' + response.message, 'error')
    }
  } catch (error) {
    console.error('更新任务失败:', error)
    showModal('错误', '更新任务失败，请重试', 'error')
  }
}

// 删除任务
const deleteTask = async (taskId) => {
  showModal('确认', '确定要删除这个任务吗？', 'info', async () => {
    try {
      const response = await api.delete(`/task/delete/${taskId}`)
      if (response.code === 0) {
        showModal('成功', '任务已删除！', 'success')
        
        // 从列表中移除任务
        const index = tasks.value.findIndex(t => t.taskId === taskId)
        if (index !== -1) {
          tasks.value.splice(index, 1)
        }
      } else {
        showModal('错误', '删除任务失败: ' + response.message, 'error')
      }
    } catch (error) {
      console.error('删除任务失败:', error)
      showModal('错误', '删除任务失败，请重试', 'error')
    }
  })
}

// 获取状态文本
const getStatusText = (statusCode) => {
  const statusMap = {
    0: '待接取',
    1: '进行中',
    2: '已完成',
    3: '已关闭'
  }
  return statusMap[statusCode] || '未知状态'
}

// 获取状态样式类
const getStatusClass = (statusCode) => {
  const classMap = {
    0: 'pending',
    1: 'in-progress',
    2: 'completed',
    3: 'closed'
  }
  return classMap[statusCode] || 'unknown'
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}

onMounted(() => {
  fetchMyTasks()
})
</script>

<style scoped>
.my-tasks-wrapper {
  min-height: 100vh;
  width: 100%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
  box-sizing: border-box;
  position: relative;
}

.my-tasks-container {
  width: 100%;
  max-width: none;
  min-height: calc(100vh - 40px);
  background: white;
  border-radius: 12px;
  box-shadow: 0 15px 30px rgba(0, 0, 0, 0.2);
  padding: 30px;
  margin: 0 auto;
  box-sizing: border-box;
}

.my-tasks-header {
  text-align: center;
  margin-bottom: 30px;
}

.my-tasks-header h1 {
  color: #333;
  font-size: 32px;
  margin-bottom: 10px;
  font-weight: 700;
}

.my-tasks-header p {
  color: #666;
  font-size: 18px;
}

.loading, .no-tasks {
  text-align: center;
  padding: 40px 0;
  color: #666;
  font-size: 18px;
}

.no-tasks .publish-button {
  margin-top: 20px;
  padding: 12px 30px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
}

.no-tasks .publish-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
}

.tasks-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 25px;
}

.task-card {
  border: 1px solid #eee;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.08);
  transition: transform 0.3s, box-shadow 0.3s;
  background: #fff;
  cursor: pointer;
}

.task-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.12);
}

.task-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 15px;
}

.task-header h3 {
  color: #333;
  font-size: 20px;
  margin: 0;
  flex: 1;
  margin-right: 10px;
}

.status-badge {
  padding: 5px 10px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 600;
  white-space: nowrap;
}

.status-badge.pending {
  background-color: #fff3cd;
  color: #856404;
}

.status-badge.in-progress {
  background-color: #cce5ff;
  color: #004085;
}

.status-badge.completed {
  background-color: #d4edda;
  color: #155724;
}

.status-badge.closed {
  background-color: #f8d7da;
  color: #721c24;
}

.task-content {
  margin-bottom: 20px;
}

.task-description {
  color: #666;
  line-height: 1.6;
  margin-bottom: 15px;
  white-space: pre-wrap;
  word-break: break-word;
}

.task-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.meta-item {
  display: flex;
  gap: 5px;
}

.meta-label {
  font-weight: 600;
  color: #333;
}

.meta-value {
  color: #666;
}

.task-actions {
  border-top: 1px solid #eee;
  padding-top: 15px;
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.edit-button,
.delete-button {
  flex: 1;
  min-width: 100px;
  padding: 10px;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
}

.edit-button {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.edit-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
}

.delete-button {
  background: linear-gradient(135deg, #dc3545 0%, #c82333 100%);
  color: white;
}

.delete-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(220, 53, 69, 0.4);
}

/* 编辑任务弹窗样式 */
.edit-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.edit-modal-container {
  background: white;
  border-radius: 10px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
  width: 90%;
  max-width: 500px;
  max-height: 90vh;
  overflow-y: auto;
}

.edit-modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #eee;
}

.edit-modal-header h3 {
  margin: 0;
  color: #333;
}

.edit-modal-close {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #999;
}

.edit-modal-close:hover {
  color: #333;
}

.edit-modal-body {
  padding: 20px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: 600;
  color: #333;
}

.form-control {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  box-sizing: border-box;
}

.form-control:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.2);
}

.status-options {
  display: flex;
  gap: 15px;
  flex-wrap: wrap;
}

.status-option {
  display: flex;
  align-items: center;
  gap: 5px;
  font-weight: normal;
}

.edit-modal-footer {
  padding: 16px 20px;
  border-top: 1px solid #eee;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.cancel-button,
.save-button {
  padding: 8px 20px;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.2s;
}

.cancel-button {
  background-color: #f5f5f5;
  color: #333;
}

.cancel-button:hover {
  background-color: #e0e0e0;
}

.save-button {
  background-color: #1890ff;
  color: white;
}

.save-button:hover {
  background-color: #40a9ff;
}

@media (max-width: 768px) {
  .my-tasks-wrapper {
    padding: 15px;
  }
  
  .my-tasks-container {
    padding: 20px;
  }
  
  .my-tasks-header h1 {
    font-size: 28px;
  }
  
  .my-tasks-header p {
    font-size: 16px;
  }
  
  .tasks-list {
    grid-template-columns: 1fr;
  }
  
  .task-actions {
    flex-direction: column;
  }
  
  .status-options {
    flex-direction: column;
    gap: 10px;
  }
}
</style>